package Client_logic;

import java.io.IOException;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import CLIENTS.Client;
import GUI.ClientInitialize;
import GUI.ClientStartForm;
import GUI.LoginForm;


/**
 * This class starts the Client Program.
 * @author ameer
 * @author waleed
 * @author bshara
 * @author kamil
 */
public class Main_class {
	final public static int DEFAULT_PORT = 5555;
	
	/**
	 * @param args
	 */
	public static void main(String[] args){

		final ClientInitialize clientinitialize = new ClientInitialize();
		clientinitialize.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		clientinitialize.setSize(400, 300);
		clientinitialize.getStartButton().addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {	
				 int port = 0;
				 
				 try{
				     	port = clientinitialize.getPort();
				     	if (port == -1 || port < 0){
				     		JOptionPane.showMessageDialog(null, "Ilegal port number");
				     		port = DEFAULT_PORT; 
				     	}
				     	if (port == 0)
				     		port = DEFAULT_PORT; 			     		
				    }
				    catch(Throwable t){
				    	port = DEFAULT_PORT; 
				    }				    
				    String  host = clientinitialize.getIP();
				    
				    try {
				      Client client= new Client(host, port);
				      ConnectionToServer.setClient(client);	      
				      LoginForm loginform = new LoginForm();
				      loginform.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
				      loginform.setSize( 400, 300 ); 
					  ClientStartForm client_startForm = new ClientStartForm(port);
					  clientinitialize.setContentPane(client_startForm);
					  loginform.setVisible( true ); 
				    } 
				    catch(IOException exception) {
				    	JOptionPane.showMessageDialog(null, "Error: Can't setup connection!"
				                + " Terminating client.");
				      System.out.println("Error: Can't setup connection!"
				                + " Terminating client.");
				      System.exit(1);
				    }
				    catch (Exception errorexceptio){
				    	JOptionPane.showMessageDialog(null, "FATAL ERROR");
				    }				   		    
			}
		});	    
		clientinitialize.setVisible(true);		    
	}
}
